package com.yu.blog.cofig.security.filter;


import com.yu.blog.constant.ConstantData;
import com.yu.blog.enums.HttpStatusEnum;
import com.yu.blog.utils.AESUtils;
import com.yu.blog.utils.RandomUtils;
import com.yu.blog.utils.RedisUtils.RedisUtils;
import com.yu.blog.utils.servletUtils.ResponseUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;


@Component
public class UsernamePasswordFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //登陆接口进行密码解密
        if (ConstantData.LoginUrl.equals(request.getRequestURI())) {
            String captcha = RandomUtils.letterUpperCase(request.getParameter("captcha"));
            String captchaCache = RandomUtils.letterUpperCase((String) redisUtils.get("captchaCode"));
            if (captcha.equals(captchaCache)) {
                HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(request) {
                    @Override
                    public String getParameter(String name) {
                        if ("password".equals(name)) {
                            return AESUtils.decryptPkcs7(request.getParameter("password").trim());
                        }
                        return super.getParameter(name);
                    }
                };
                filterChain.doFilter(httpServletRequestWrapper, response);
            }else {
                ResponseUtil.setFailedResponse(response, HttpStatusEnum.CAPTCHA_ERROR);
            }
            return;
        }
        filterChain.doFilter(request, response);
    }
}
